// 游戏主类
class Game {
    constructor() {
        this.board = null;
        this.ui = null;
        this.currentLevel = 0;
        this.currentRound = 0;  // 改为从0开始
        this.lives = CONFIG.initialLives;
        this.attackPower = 0;
        this.monstersDefeated = 0;
        this.bossDefeated = 0;  // 新增：记录击败的Boss数量
        this.targets = [];      // 新增：存储当前关卡的目标
        this.bossHealth = CONFIG.bossHealth;
        this.isConnecting = false;
        this.connectedCells = [];
        this.gameOver = false;
        this.playerPosition = { row: 6, col: 3 }; // 添加主角位置
        this.currentConnType='Free'; // 当前连接类型
        this.maxRounds = 0; // 添加最大回合数属性
        // 定义可以增加攻击力的元素类型数组
        this.powerIncreasingElements = [
            CONFIG.elementTypes.MONSTER_BLUE,
            CONFIG.elementTypes.MONSTER_PINK,
            CONFIG.elementTypes.MONSTER_RED,
            CONFIG.elementTypes.MONSTER_YELLOW,
            CONFIG.elementTypes.MONSTER_GREEN,
            CONFIG.elementTypes.GEM,
            CONFIG.elementTypes.WOOD
        ];
    }

    // 初始化游戏
    init() {
        this.board = new Board(this);
        this.ui = new UI(this);
        this.interactionEnabled = true; // 添加交互控制变量
        
        this.loadLevel(1); // 加载第一关
        this.setupEventListeners();
        
        this.ui.updateUI();
    }

    // 加载关卡
    loadLevel(levelIndex) {
        console.log('Loading level:', levelIndex);
        console.log('Available levels:', Object.keys(CONFIG.levels));
        
        // 确保levelIndex是有效的
        if (!CONFIG.levels[levelIndex]) {
            console.error(`关卡 ${levelIndex} 不存在`);
            console.log('CONFIG.levels:', CONFIG.levels);
            levelIndex = 1; // 默认加载第一关
        }
        
        this.currentLevel = levelIndex;
        const level = CONFIG.levels[levelIndex];
        
        // 更新UI显示当前关卡名称
        document.getElementById('level').textContent = level.name;
        
        // 重置游戏状态
        this.currentRound = 0;  // 改为从0开始
        this.attackPower = 0;
        this.monstersDefeated = 0;
        this.bossDefeated = 0;  // 重置Boss击败数量
        this.targets = level.target.map(target => ({...target}));  // 复制目标数组
        this.bossHealth = level.bossHealth || CONFIG.bossHealth;
        this.isConnecting = false;
        this.connectedCells = [];
        this.gameOver = false;
        this.maxRounds = level.maxRounds || 10; // 设置关卡最大回合数，如果未配置则默认10回合
        
        // 初始化棋盘
        this.board.initBoard(level.initialBoard);
        
        // 查找并设置主角初始位置
        for (let row = 0; row < CONFIG.boardSize; row++) {
            for (let col = 0; col < CONFIG.boardSize; col++) {
                if (this.board.getCell(row, col) === CONFIG.elementTypes.PLAYER) {
                    this.playerPosition = { row, col };
                    break;
                }
            }
        }
        
        // 更新UI
        this.ui.updateUI();
    }

    // 设置事件监听器
    setupEventListeners() {
        const gameBoard = document.getElementById('game-board');
        
        // 棋盘点击事件
        gameBoard.addEventListener('click', (e) => {
            if (this.gameOver) return;
            
            const cell = e.target.closest('.cell');
            if (!cell) return;
            
            const row = parseInt(cell.dataset.row);
            const col = parseInt(cell.dataset.col);
            
            this.handleCellClick(row, col);
        });
        
        // 攻击按钮点击事件
        const attackButton = document.getElementById('attack-button');
        attackButton.addEventListener('click', () => {
            if (this.gameOver) return;
            
            this.endRound();
        });
        
        // 撤销按钮点击事件
        const undoButton = document.getElementById('undo-button');
        undoButton.addEventListener('click', () => {
            if (this.gameOver) return;
            
            if (this.isConnecting) {
                this.board.clearAllConnections();
            }
        });
    }

    // 处理格子点击
    handleCellClick(row, col) {
        // 检查单元格是否正在动画中
        const cellElement = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
        if (cellElement && cellElement.classList.contains('animating')) {
            return; // 动画期间不允许点击该单元格
        }
        
        // 检查是否点击到主角
        if (this.board.isPlayerPosition(row, col)) {
            // 如果正在连接中，清除所有连接
            if (this.isConnecting) {
                this.board.clearAllConnections();
            }
            return;
        }
        
        if (this.isConnecting) {
            console.log('tryConnectCell')
            // 已经在连接中，尝试连接到新格子
            this.tryConnectCell(row, col);
        } else {
            console.log('startConnection')
            // 开始新的连接
            this.startConnection(row, col);
        }
    }

    // 开始连接
    startConnection(row, col) {
        const cell = this.board.getCell(row, col);
        
        // 检查是否可以开始连接
        if (!this.canStartConnection(cell)) return;
        
        // 检查是否与主角相邻
        if (!this.isAdjacent(this.playerPosition.row, this.playerPosition.col, row, col)) return;
        
        this.isConnecting = true;
        this.connectedCells = [{row, col}];
        
        // 计算初始攻击力
        if (cell === CONFIG.elementTypes.MONSTER_BLUE ||
            cell === CONFIG.elementTypes.MONSTER_PINK ||
            cell === CONFIG.elementTypes.MONSTER_RED ||
            cell === CONFIG.elementTypes.MONSTER_YELLOW ||
            cell === CONFIG.elementTypes.MONSTER_GREEN) {
            this.attackPower = 1;
        }
        if(this.isSmallMonster(cell)){
            this.currentConnType=cell
        } 
        console.log('第一次连接的类型:'+cell)
        // 更新UI
        this.ui.highlightCell(row, col);
        this.ui.updateUI(); // 添加UI更新

        // 绘制箭头
        this.board.drawConnectionArrow(this.playerPosition.row, this.playerPosition.col, row, col);
    }

    // 尝试连接到新格子
    tryConnectCell(row, col) {
        console.log('尝试连接到:', row, col);
        const newCell = this.board.getCell(row, col);
        const lastCell = this.connectedCells[this.connectedCells.length - 1];
        
        // 检查是否可以连接
        if (!this.canConnect(lastCell.row, lastCell.col, row, col, newCell)) return;
        
        // 检查是否已经连接过
        if (this.isAlreadyConnected(row, col)) return;
        
        // 添加到连接列表
        this.connectedCells.push({row, col});
        
        // 实时计算攻击力（连接的怪物数量）
        const monsterCount = this.connectedCells.filter(cell => {
            const cellType = this.board.getCell(cell.row, cell.col);
            return this.powerIncreasingElements.includes(cellType);
        }).length;

        // 计算箱子消耗的攻击力
        const boxCount = this.connectedCells.filter(cell => {
            return this.board.getCell(cell.row, cell.col) === CONFIG.elementTypes.BOX;
        }).length;

        // 计算Boss消耗的攻击力
        const bossCount = this.connectedCells.filter(cell => {
            return this.board.getCell(cell.row, cell.col) === CONFIG.elementTypes.BOSS;
        }).length;

        // 更新攻击力（怪物数量减去箱子和Boss消耗）
        const bossHealth = bossCount * this.bossHealth;
        this.attackPower = Math.max(0, monsterCount - (boxCount * 3) - bossHealth);

        
        // 更新UI
        this.ui.highlightCell(row, col);
        this.ui.drawConnectionLine(lastCell.row, lastCell.col, row, col);
        this.ui.updateUI(); // 实时更新UI显示
        
        // 检查是否连接到宝石或木材
        if (newCell === CONFIG.elementTypes.GEM) {
            this.currentConnType ='Free';
        }

        // 保存连接类型，如果newCell类型是小怪，则保存
        if(this.isSmallMonster(newCell)){
            this.currentConnType=newCell;
        }
        
        console.log('已成功连接，当前连接类型:', this.currentConnType);
        // 绘制箭头
        this.board.drawConnectionArrow(lastCell.row, lastCell.col, row, col);
    }

    //判断某格子是否为普通小怪
    isSmallMonster(cellType){
        return cellType === CONFIG.elementTypes.MONSTER_BLUE || 
               cellType === CONFIG.elementTypes.MONSTER_PINK || 
               cellType === CONFIG.elementTypes.MONSTER_RED ||
               cellType === CONFIG.elementTypes.MONSTER_YELLOW ||
               cellType === CONFIG.elementTypes.MONSTER_GREEN;
    }

    // 检查是否可以开始连接
    canStartConnection(cellType) {
        // 只能从主角相邻的怪物、宝石或木材开始连接
        return (cellType === CONFIG.elementTypes.MONSTER_BLUE ||
                cellType === CONFIG.elementTypes.MONSTER_PINK ||
                cellType === CONFIG.elementTypes.MONSTER_RED ||
                cellType === CONFIG.elementTypes.MONSTER_YELLOW ||
                cellType === CONFIG.elementTypes.MONSTER_GREEN ||
                cellType === CONFIG.elementTypes.GEM ||
                cellType === CONFIG.elementTypes.WOOD); // 添加木材作为连接起点
    }

    // 检查是否可以连接到新格子
    canConnect(lastRow, lastCol, newRow, newCol, newCellType) {
        // 检查是否相邻
        if (!this.isAdjacent(lastRow, lastCol, newRow, newCol)) return false;
        
        // 如果新格子是树木，直接返回 false
        if (newCellType === CONFIG.elementTypes.TREE) return false;
        
        // 记录日志
        console.log('当前连接类型:', this.currentConnType, '新格子类型:', newCellType);        
        // 如果是自由连接状态，可以连接任意怪物
        if (this.currentConnType === 'Free') {
            return true;
        }

        // 连接相同类型的怪物
        if (this.currentConnType === newCellType && 
            (newCellType === CONFIG.elementTypes.MONSTER_BLUE ||
             newCellType === CONFIG.elementTypes.MONSTER_PINK ||
             newCellType === CONFIG.elementTypes.MONSTER_RED ||
             newCellType === CONFIG.elementTypes.MONSTER_YELLOW ||
             newCellType === CONFIG.elementTypes.MONSTER_GREEN)) {
            return true;
        }
        
        // 连接宝石或木材
        if (newCellType === CONFIG.elementTypes.GEM || 
            newCellType === CONFIG.elementTypes.WOOD) {
            return true;
        }
        
        // 连接木箱，需要至少3点攻击力
        if (newCellType === CONFIG.elementTypes.BOX) {
            return this.attackPower >= 3;
        }
        
        // 连接Boss，需要足够的攻击力
        if (newCellType === CONFIG.elementTypes.BOSS) {
            console.log('尝试连接Boss:', {
                attackPower: this.attackPower,
                bossHealth: this.bossHealth,
                canConnect: this.attackPower >= this.bossHealth
            });
            // 确保攻击力大于等于Boss血量
            return this.attackPower >= this.bossHealth;
        }
        
        return false;
    }

    // 检查两个格子是否相邻
    isAdjacent(row1, col1, row2, col2) {
        const rowDiff = Math.abs(row1 - row2);
        const colDiff = Math.abs(col1 - col2);
        
        // 相邻格子（包括对角线）
        return (rowDiff <= 1 && colDiff <= 1) && !(rowDiff === 0 && colDiff === 0);
    }

    // 检查格子是否已经连接过
    isAlreadyConnected(row, col) {
        return this.connectedCells.some(cell => cell.row === row && cell.col === col);
    }

    // 结束当前连接
    endConnection() {
        if (!this.isConnecting || this.connectedCells.length < 1) return;
        
        // 清除所有箭头
        this.board.clearAllArrows();
        
        // 收集所有需要填充的空格
        let emptyCells = [];
        
        // 记录是否有木箱被打破
        let brokenBoxCount = 0;
        
        // 移除连接的格子并记录最后一个位置
        let lastCell = null;
        for (const cell of this.connectedCells) {
            const cellType = this.board.getCell(cell.row, cell.col);
            
            // 统计击败的怪物
            if (cellType === CONFIG.elementTypes.MONSTER_BLUE ||
                cellType === CONFIG.elementTypes.MONSTER_PINK ||
                cellType === CONFIG.elementTypes.MONSTER_RED ||
                cellType === CONFIG.elementTypes.MONSTER_YELLOW ||
                cellType === CONFIG.elementTypes.MONSTER_GREEN) {
                this.monstersDefeated++;
                this.updateTargetProgress("monsters", this.monstersDefeated);
            }
            
            // 处理特殊格子
            if (cellType === CONFIG.elementTypes.BOX) {
                // 记录木箱被打破
                brokenBoxCount++;
            } else if (cellType === CONFIG.elementTypes.BOSS) {
                this.bossDefeated++;  // 改为递增Boss击败数量，而不是设为1
                this.updateTargetProgress("boss", this.bossDefeated);
            }
            
            // 清空格子
            this.board.setCell(cell.row, cell.col, CONFIG.elementTypes.EMPTY);
            emptyCells.push({row: cell.row, col: cell.col});
            lastCell = cell;
        }
        
        // 处理打破木箱后的木材掉落逻辑
        if (brokenBoxCount > 0 && emptyCells.length > 0) {
            // 获取当前关卡设置
            const level = CONFIG.levels[this.currentLevel];
            let woodDropRate = 0;
            
            // 使用顶层的木材掉落率，而不是从回合范围中获取
            woodDropRate = level.woodDropRate || 0;
            
            // 如果没有定义顶层掉落率，则使用配置中的全局掉落率
            if (woodDropRate === 0) {
                woodDropRate = CONFIG.woodDropRate || 0;
            }
            console.log('木材掉落率:', woodDropRate);
            // 为每个被打破的木箱尝试生成一个木材（最多生成brokenBoxCount个）
            for (let i = 0; i < brokenBoxCount; i++) {
                // 根据概率决定是否生成木材
                if (woodDropRate > 0 && Math.random() * 100 < woodDropRate) {
                    // 随机选择一个空位置放置木材
                    const randomIndex = Math.floor(Math.random() * emptyCells.length);
                    const randomCell = emptyCells[randomIndex];
                    
                    // 将该位置设置为木材
                    this.board.setCell(randomCell.row, randomCell.col, CONFIG.elementTypes.WOOD);
                    
                    // 从空格列表中移除这个位置
                    emptyCells.splice(randomIndex, 1);
                }                    
            }
        }
        
        // 移动主角到最后连接的格子位置
        if (lastCell) {
            this.movePlayer(lastCell.row, lastCell.col);
        }
        
        // 立即填充剩余的空格
        this.fillSpecificCells(emptyCells);
        
        // 重置连接状态
        this.isConnecting = false;
        this.connectedCells = [];
        this.currentConnType='Free'; // 重置连接类型
        
        // 更新UI
        this.ui.clearHighlights();
        this.ui.updateUI();
    }

    // 新增：更新目标进度
    updateTargetProgress(targetType, currentValue) {
        for (let target of this.targets) {
            if (target.type === targetType) {
                target.currentValue = Math.min(currentValue, target.count);
                // 更新描述文本
                if (targetType === "monsters") {
                    target.description = `怪物: ${target.currentValue}/${target.count}`;
                } else if (targetType === "boss") {
                    target.description = `击败Boss: ${target.currentValue}/${target.count}`;
                }
            }
        }
    }

    // 新增：检查是否满足所有胜利条件
    checkWinCondition() {
        const allTargetsMet = this.targets.every(target => 
            (target.currentValue || 0) >= target.count
        );
        
        if (allTargetsMet) {
            this.winGame();
        }
    }

    // 填充指定的空格
    fillSpecificCells(cells) {
        if (!cells || cells.length === 0) return;
        
        const level = CONFIG.levels[this.currentLevel];
        
        // 优化：只标记正在动画的单元格，而不是整个棋盘
        cells.forEach(cell => {
            const cellElement = document.querySelector(`.cell[data-row="${cell.row}"][data-col="${cell.col}"]`);
            if (cellElement) {
                cellElement.classList.add('animating');
            }
        });
        
        // 创建动画序列
        const animationPromises = [];
        
        for (const cell of cells) {
            if (this.board.getCell(cell.row, cell.col) === CONFIG.elementTypes.EMPTY) {
                const newElement = this.generateElementBasedOnProbability();
                // 使用带动画的填充方法
                const promise = this.board.fillCellWithAnimation(cell.row, cell.col, newElement);
                animationPromises.push(promise);
            }
        }
        
        // 所有动画完成后移除标记
        Promise.all(animationPromises).then(() => {
            cells.forEach(cell => {
                const cellElement = document.querySelector(`.cell[data-row="${cell.row}"][data-col="${cell.col}"]`);
                if (cellElement) {
                    cellElement.classList.remove('animating');
                }
            });
        });
    }

    // 根据概率生成元素
    generateElementBasedOnProbability() {
        const level = CONFIG.levels[this.currentLevel];
        
        // 根据当前回合获取相应的掉落概率
        let dropRate = level.defaultDropRate;
        
        // 查找当前回合所在的范围
        for (const range of level.roundRanges) {
            if (this.currentRound >= range.startRound && this.currentRound <= range.endRound) {
                dropRate = range.dropRate;
                break;
            }
        }
        
        // 随机生成 0-100 的数
        const rand = Math.floor(Math.random() * 100);
        
        // 计算累积概率并确定元素类型
        let cumulative = 0;
        
        if (dropRate.monster_blue) {
            cumulative += dropRate.monster_blue;
            if (rand < cumulative) return CONFIG.elementTypes.MONSTER_BLUE;
        }
        
        if (dropRate.monster_pink) {
            cumulative += dropRate.monster_pink;
            if (rand < cumulative) return CONFIG.elementTypes.MONSTER_PINK;
        }
        
        if (dropRate.monster_red) {
            cumulative += dropRate.monster_red;
            if (rand < cumulative) return CONFIG.elementTypes.MONSTER_RED;
        }
        
        if (dropRate.monster_yellow) {
            cumulative += dropRate.monster_yellow;
            if (rand < cumulative) return CONFIG.elementTypes.MONSTER_YELLOW;
        }
        
        if (dropRate.monster_green) {
            cumulative += dropRate.monster_green;
            if (rand < cumulative) return CONFIG.elementTypes.MONSTER_GREEN;
        }
        
        if (dropRate.gem) {
            cumulative += dropRate.gem;
            if (rand < cumulative) return CONFIG.elementTypes.GEM;
        }
        
        if (dropRate.box) {
            cumulative += dropRate.box;
            if (rand < cumulative) return CONFIG.elementTypes.BOX;
        }
        
        // 默认返回蓝色怪物
        return CONFIG.elementTypes.MONSTER_BLUE;
    }

    // 结束回合
    endRound() {
        // 结束当前连接
        this.endConnection();
        
        // 增加回合数（移到这里，在重置攻击力之前）
        this.currentRound++;
        
        // 重置攻击力
        this.attackPower = 0;
        
        // 检查是否达成目标
        this.checkWinCondition();
        
        // 如果没有达成目标，继续游戏
        if (!this.gameOver) {
            // 检查是否达到最大回合数
            if (this.currentRound >= this.maxRounds) {
                this.loseGame();
                return;
            }
        }
        
        // 更新UI
        this.ui.updateUI();
    }

    // 填充空格（结束回合时不再需要填充，因为每次连接后都会填充）
    fillEmptyCells() {
        for (let row = 0; row < CONFIG.boardSize; row++) {
            for (let col = 0; col < CONFIG.boardSize; col++) {
                if (this.board.getCell(row, col) === CONFIG.elementTypes.EMPTY) {
                    const newElement = this.generateElementBasedOnProbability();
                    this.board.setCell(row, col, newElement);
                }
            }
        }
    }

    // 赢得游戏
    winGame() {
        this.gameOver = true;
        this.ui.showGameOver(true);
    }

    // 输掉游戏
    loseGame() {
        this.gameOver = true;
        this.ui.showGameOver(false);
    }

    // 重新开始游戏
    restart() {
        this.loadLevel(this.currentLevel);
    }

    // 移动主角到新位置
    movePlayer(row, col) {
        // 记录主角原始位置
        const originalRow = this.playerPosition.row;
        const originalCol = this.playerPosition.col;
        
        // 清除原位置的主角
        this.board.setCell(originalRow, originalCol, CONFIG.elementTypes.EMPTY);
        
        // 更新主角位置
        this.playerPosition = { row, col };
        
        // 在新位置设置主角
        this.board.setCell(row, col, CONFIG.elementTypes.PLAYER);
        
        // 填充原始位置
        this.fillSpecificCells([{row: originalRow, col: originalCol}]);
        
        // 更新棋盘显示
        this.board.updateBoard();
    }

    attackBox(boxPosition) {
        // 检查是否有足够的攻击力来打箱子
        if (this.attackPower < 3) {
            console.log('攻击力不足以打破箱子');
            return false;
        }
        
        // 找到对应位置的箱子
        const box = this.boxes.find(b => b.x === boxPosition.x && b.y === boxPosition.y);
        if (box) {
            // 移除箱子
            this.boxes = this.boxes.filter(b => b !== box);
            // 扣除3点攻击力
            this.attackPower -= 3;
            return true;
        }
        return false;
    }
}